//
//  EFAPjtDeviceAddVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/14.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAPjtDeviceAddVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFAPjtAddTCell.h"
#import "EFAMatAddImgTCell.h"
#import "EFAModel.h"
#import "EFADeviceVC.h"
#import "EFAMsgVC.h"
#import "EFAPjtMapVC.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "NSDate+XDTimerFormatter.h"
#import "EFAPjtPlaceSelVC.h"
#import "EFAUtySelDevTypeTVC.h"
#import "EFAUtySelDevSubUUIDVC.h"
#import "EFAUtyQRScanVC.h"
#import "EFAPjtDevSeaICCIDVC.h"
#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import "XDQiniuManager.h"

@interface EFAPjtDeviceAddVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFAPjtAddTCellDelegate, EFAMatAddImgTCellDelegate, TZImagePickerControllerDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *saveBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *batchBarBtnItem;
@property (nonatomic, assign) EFAPjtDeviceAddVCType viewType;
@property (nonatomic, strong) NSArray<NSArray<EFAPjtAddViewCfg *> *> *dataArray;

@property (nonatomic, strong) EFADevPubModel *devPubModel;  ///< 设备图片相关
@end

static NSString *const kReuseCellId = @"EFAPjtAddTCell";
static NSString *const kReuseImgCellId = @"EFAMatAddImgTCell";

@implementation EFAPjtDeviceAddVC

#pragma mark - life cycle
- (instancetype)initWithViewType:(EFAPjtDeviceAddVCType)viewType {
    self = [super init];
    if (self) {
        _viewType = viewType;
        if (viewType == EFAPjtDeviceAddVCTypeAdd) {
            _deviceItem = [[EFADeviceListItem alloc] init];
        }
    }
    return self;
}

- (instancetype)init {
    NSAssert(NO, @"use initWithViewType");
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initLogicData];
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initLogicData {
    BOOL canEdit = (self.viewType == EFAPjtDeviceAddVCTypeDetail) ? NO : YES;
    self.devPubModel = [[EFADevPubModel alloc] initWithImgUrlArray:self.deviceItem.efairydevice_imgurl_list canEdit:canEdit];
}

- (void)initNavigationBar {
    NSArray *titleArray = @[@"新增设备", @"编辑设备", @"设备详情"];
    self.navigationItem.title = titleArray[self.viewType];
    if (self.viewType != EFAPjtDeviceAddVCTypeDetail) {
        self.navigationItem.rightBarButtonItem = self.saveBarBtnItem;
        [self.saveBarBtnItem setEnabled:NO];
    }
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    // --------测试使用--------
//    [self.navigationItem setRightBarButtonItems:@[self.saveBarBtnItem, self.batchBarBtnItem] animated:NO];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    UINib *imgNib = [UINib nibWithNibName:kReuseImgCellId bundle:nil];
    [self.tableView registerNib:imgNib forCellReuseIdentifier:kReuseImgCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //    self.tableView.emptyDataSetDelegate = self;
    //    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    //    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
    //    [self.tableView.mj_header beginRefreshing];
    if (self.viewType == EFAPjtDeviceAddVCTypeDetail) {
        [self requestDeviceDetail];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//#pragma mark - DZNEmptyDataSetSource
//- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
//    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
//    return [[NSAttributedString alloc] initWithString:@"当前没有项目" attributes:dic];
//}
//
//- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
//    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
//    return nil;
//}
//
////- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
////    return -100.0;
////}
//#pragma mark - DZNEmptyDataSetDelegate
//- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
//    return YES;
//}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section < self.dataArray.count) {
        return self.dataArray[section].count;
    }
    return (self.devPubModel.imgMaxCnt != 0) ? 1 : 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section < self.dataArray.count) {
        EFAPjtAddTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
        if (indexPath.row < self.dataArray[indexPath.section].count) {
            [cell configViewWithViewCfg:self.dataArray[indexPath.section][indexPath.row]];
        }
        cell.delegate = self;
        return cell;
    } else {
        EFAMatAddImgTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseImgCellId forIndexPath:indexPath];
        [cell configViewWithDevPubModel:self.devPubModel];
        cell.delegate = self;
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 14.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.viewType == EFAPjtDeviceAddVCTypeDetail) {
        return;
    }
    if (indexPath.section < self.dataArray.count) {
        if (indexPath.row < self.dataArray[indexPath.section].count) {
            EFAPjtAddViewCfg *cfg = self.dataArray[indexPath.section][indexPath.row];
            if ([cfg.keyDes isEqualToString:@"设备定位"]) {
                [self jumpToSelectAddressWithCfg:cfg];
            } else if ([cfg.keyDes isEqualToString:@"设备类型"]) {
                [self jumpToSelectDeviceType];
            } else if ([cfg.keyDes isEqualToString:@"设备主编码"]) {
                [self jumpToSelectDeviceUUID];
            } else if ([cfg.keyDes isEqualToString:@"设备从编码"]) {
                [self jumpToSelectDeviceSubUUID];
            }
        }
    }
}

#pragma mark - EFAPjtAddTCellDelegate
- (void)pjtAddTCell:(EFAPjtAddTCell *)cell editChanged:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.section < self.dataArray.count) {
        if (indexPath.row < self.dataArray[indexPath.section].count) {
            EFAPjtAddViewCfg *cfg = self.dataArray[indexPath.section][indexPath.row];
            cfg.value = textField.text;
            if ([cfg.keyDes isEqualToString:@"设备名称"]) {
                self.deviceItem.efairydevice_name = textField.text;
            }
        }
    }
    self.saveBarBtnItem.enabled = [self checkSaveBtnState];
}
- (void)pjtAddTCell:(EFAPjtAddTCell *)cell textViewDidChanged:(UITextView *)textView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.section < self.dataArray.count) {
        if (indexPath.row < self.dataArray[indexPath.section].count) {
            EFAPjtAddViewCfg *cfg = self.dataArray[indexPath.section][indexPath.row];
            cfg.value = textView.text;
            if ([cfg.keyDes isEqualToString:@"设备描述"]) {
                self.deviceItem.efairydevice_description = textView.text;
            }
        }
    }
    self.saveBarBtnItem.enabled = [self checkSaveBtnState];
    
    // 让其自动扩展
    [self.tableView beginUpdates];
    [self.tableView endUpdates];
}
- (void)pjtAddTCell:(EFAPjtAddTCell *)cell scanBtnTapped:(UIButton *)btn {
    EFAUtyQRScanVC *vc = [[EFAUtyQRScanVC alloc] init];
    vc.successHandle = ^(NSString *qrCodeStr) {
        NSString *result = [self encodingScanResult:qrCodeStr];
        self.deviceItem.efairydevice_description = result;
        self.dataArray = [self refreshDataArray];
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}

#pragma mark - EFAMatAddImgTCellDelegate
- (void)matAddImgTCell:(EFAMatAddImgTCell *)cell collectionView:(UICollectionView *)collectionView addWithIndexPath:(NSIndexPath *)cIndexPath {
    // 添加照片
    NSInteger maxCnt = self.devPubModel.imgMaxCnt - self.devPubModel.image_list.count;
    TZImagePickerController * pickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCnt delegate:self];
    pickerVC.allowPickingVideo = NO;
    pickerVC.allowTakePicture = NO;
    pickerVC.allowPickingOriginalPhoto = NO;
    [self presentViewController:pickerVC animated:YES completion:nil];
}
- (void)matAddImgTCell:(EFAMatAddImgTCell *)cell collectionView:(UICollectionView *)collectionView delWithIndexPath:(NSIndexPath *)cIndexPath {
    [self.devPubModel removePublishItemAtIndex:cIndexPath.row];
    [self refreshWholeView];
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if (isSelectOriginalPhoto) {
        [assets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            // 上面一个占用内存太大，导致崩溃。所以只能考虑下面这个获取原图的方法。
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:obj completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                NSLog(@"获取原图--%@, (%zd)", info, isDegraded);
                if (!isDegraded) {
                    if (idx < photos.count) {
                        [self.devPubModel addPublishItemsWithImgArray:@[photos[idx]] originalDataArray:@[data]];
                        [self refreshWholeView];
                    }
                }
            }];
        }];
    } else {
        [self.devPubModel addPublishItemsWithImgArray:photos originalDataArray:nil];
        [self refreshWholeView];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    NSLog(@"选择照片缩略图 = %@", photos);
    NSLog(@"选择照片原始的assets = %@", assets);
    NSLog(@"选取照片之后的infos = %@", infos);
}

#pragma mark - event response
- (void)addBarBtnTapped:(UIBarButtonItem *)item {
    if (![self checkUserInput]) {
        return;
    }
    
    // 图片上传成功、发布未成功的情况下，直接去发布即可
    if (self.devPubModel.isImgUpload) {
        [self requestAddOrEditDevice];
        return;
    }
    
    // 上传图片
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"上传图片...";
    
    [[XDQiniuManager sharedInstance] uploadImages:self.devPubModel.needUploadImgArray progress:^(NSString *key, float percent) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = percent;
        });
    } success:^(NSArray<NSString *> *urlArray) {
        [hud hideAnimated:NO];
        [self.devPubModel updateImgUrlWithArray:urlArray];
        // 发表到服务器
        [self requestAddOrEditDevice];
        NSLog(@"开始发表到服务器");
    } failure:^(NSString *error) {
        NSLog(@"上传图片失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:error];
    }];
}
- (void)batchBarBtnTapped:(UIBarButtonItem *)item {
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"海普庆" ofType:@"txt"]];
    NSString *content = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
    NSArray<NSString *> *arr = [content componentsSeparatedByString:@"\n"];
    NSLog(@"读取的数据长度 : %ld", (unsigned long)arr.count);
    NSLog(@"读取的内容 : %@", arr);
    
    for (NSInteger i = 0; i < arr.count; i++) {
        for (NSInteger j = i+1; j < arr.count; j++) {
            if ([arr[i] isEqualToString:arr[j]]) {
                NSLog(@"发现重复ICCID : %@", arr[i]);
            }
        }
    }
    
    NSMutableArray<NSString *> *temp = [NSMutableArray arrayWithCapacity:arr.count];
    for (NSString *ori in arr) {
        if (!ori.length) {
            continue;
        }
        
        BOOL isFind = NO;
        for (NSString *intemp in temp) {
            if ([ori isEqualToString:intemp]) {
                isFind = YES;
                break;
            }
        }
        if (!isFind) {
            [temp addObject:ori];
        }
    }
    NSLog(@"统计出来的未重复的总数量是:%ld", (unsigned long)temp.count);
    
    [temp enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.length > 0) {
            [self requestAddDeviceWithDeviceICCID:obj cntIndex:idx];
        }
    }];
}
#pragma mark - private methods
- (void)jumpToSelectDeviceType {
    EFAUtySelDevTypeTVC *vc = [[EFAUtySelDevTypeTVC alloc] initWithViewType:EFAUtySelDevTypeTVCDev];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.system_type_id = 10; ///< 固定目前只能选择电气火灾监控系统
    vc.successHandle = ^(NSInteger device_type_id) {
        self.deviceItem.efairydevice_device_type_id = device_type_id;
        [self.deviceItem refreshDeviceTypeName];
        self.dataArray = [self refreshDataArray];
        [self refreshWholeView];
    };
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)jumpToSelectDeviceUUID {
    UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    EFAPjtDevSeaICCIDVC *vc = [mainSb instantiateViewControllerWithIdentifier:@"EFAPjtDevSeaICCIDVC"];
    vc.successHandle = ^(NSString *iotICCID) {
        self.deviceItem.efairydevice_main_uuid = iotICCID;
        self.dataArray = [self refreshDataArray];
        [self refreshWholeView];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)jumpToSelectDeviceSubUUID {
    BOOL needSubUUID = [[EFADeviceProtocolModel sharedInstance] deviceTypeNeedSubUUIDWithType:self.deviceItem.efairydevice_device_type_id];
    if (!needSubUUID) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"当前设备类型，从编码不可以编辑"];
        return;
    }
    
    EFAUtySelDevSubUUIDVC *vc = [[EFAUtySelDevSubUUIDVC alloc] init];
    vc.successHandle = ^(NSString *subUUID) {
        self.deviceItem.efairydevice_sub_uuid = subUUID;
        self.dataArray = [self refreshDataArray];
        [self refreshWholeView];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)jumpToSelectAddressWithCfg:(EFAPjtAddViewCfg *)cfg {
    EFAPjtPlaceSelVC *vc = [[EFAPjtPlaceSelVC alloc] init];
    vc.successHandle = ^(CLLocationCoordinate2D location, NSString *address) {
        cfg.value = address;
        self.deviceItem.efairydevice_address = address;
        self.deviceItem.efairydevice_location_lat = location.latitude;
        self.deviceItem.efairydevice_location_lng = location.longitude;
        [self refreshWholeView];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

- (BOOL)checkUserInput {
    for (NSArray *sArray in self.dataArray) {
        for (EFAPjtAddViewCfg *cfg in sArray) {
            if (cfg.value.length < cfg.valueMinLen || cfg.value.length > cfg.valueMaxLen) {
                [MBProgressHUD showPromptWithAutoHideInView:self.view message:cfg.prompt];
                return NO;
            }
        }
    }
    return YES;
}

- (BOOL)checkSaveBtnState {
//    for (NSArray *sArray in self.dataArray) {
//        for (EFAPjtAddViewCfg *cfg in sArray) {
//            if (cfg.value.length < cfg.valueMinLen || cfg.value.length > cfg.valueMaxLen) {
//                return NO;
//            }
//        }
//    }
    return YES;
}

- (NSMutableDictionary *)parametersDictionary {
    NSMutableDictionary *mDic = [[NSMutableDictionary alloc] init];
    for (NSArray *sArray in self.dataArray) {
        for (EFAPjtAddViewCfg *cfg in sArray) {
            NSString *value = cfg.value ? cfg.value : @"";
            [mDic setObject:value forKey:cfg.key];
            // Key-Value来更改原始值
            [self.deviceItem setValue:value forKey:cfg.key];
        }
    }
    // 没有的参数也加进来，比如坐标
    [mDic setObject:@(self.deviceItem.efairydevice_location_lat) forKey:@"efairydevice_location_lat"];
    [mDic setObject:@(self.deviceItem.efairydevice_location_lng) forKey:@"efairydevice_location_lng"];
    [mDic setObject:@(self.project_id) forKey:@"efairydevice_project_id"];
    [mDic setObject:@(self.deviceItem.efairydevice_belong_system) forKey:@"efairydevice_belong_system"];
    [mDic setObject:@(self.deviceItem.efairydevice_device_type_id) forKey:@"efairydevice_device_type_id"];
    [mDic setObject:@(self.deviceItem.efairydevice_id) forKey:@"efairydevice_id"];
    // 主从编码组合成UUID
    [self.deviceItem composeToUUID];
    [mDic setObject:self.deviceItem.efairydevice_uuid forKey:@"efairydevice_uuid"];
    // 设备安装时间
    if (self.viewType == EFAPjtDeviceAddVCTypeEdit) {
        NSString *installTime = self.deviceItem.efairydevice_install_time ? self.deviceItem.efairydevice_install_time : @"";
        [mDic setObject:installTime forKey:@"efairydevice_install_time"];
    } else {
        NSDate *date = [NSDate date];
        [mDic setObject:[date xd_yyyy_MM_ddHHmmss] forKey:@"efairydevice_install_time"];
    }
    // 设备竣工图、同时把ulr放回deviceItem
    [mDic setObject:self.devPubModel.urlArray forKey:@"efairydevice_imgurl_list"];
    self.deviceItem.efairydevice_imgurl_list = [self.devPubModel.urlArray mutableCopy];
    
    return mDic;
}

- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.saveBarBtnItem.enabled = [self checkSaveBtnState];
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
//    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    //    [self requestUserListWithHeader:isHeader];
}

- (void)backToParent {
    if (self.successHandle) {
        self.successHandle();
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *    @brief    检查扫描结果里是否有中文，如果有则进行转码处理（只处理了gbk和utf-8类型的中文字符）
 *
 *    @param text 扫描结果字符串
 *
 *    @return    转码后的字符串
 */
- (NSString *)encodingScanResult:(NSString *)text {
    NSString *result = text;//返回的扫描结果
    NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];//如果中文是utf-8编码转gbk结果为空(还没搞明白)
    if (retStr)//如果扫描中文乱码则需要处理，否则不处理
    {
        NSInteger max = [text length];
        char *nbytes = malloc(max + 1);
        for (NSInteger i = 0; i < max; i++) {
            unichar ch = [text characterAtIndex: i];
            nbytes[i] = (char) ch;
        }
        nbytes[max] = '\0';
        result = [NSString stringWithCString: nbytes
                                  encoding: enc];
    }
    return result;
}

#pragma mark - network request
- (void)requestAddOrEditDevice {
    //请求服务器
    if (self.viewType == EFAPjtDeviceAddVCTypeAdd) {
        [self requestAddDevice];
    } else {
        [self requestEditDevice];
    }
}

- (void)requestAddDevice {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [self parametersDictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    NSLog(@"添加设备的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiPjtMgrDevice] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"添加设备返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"添加设备成功"];
        temp.completionBlock = ^{
            [self backToParent];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"添加设备失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestAddDeviceWithDeviceICCID:(NSString *)iccid cntIndex:(NSInteger)cntIndex {
    if (iccid.length != 20) {
        return;
    }
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    EFADeviceListItem *deviceInfo = [[EFADeviceListItem alloc] init];
    deviceInfo.efairydevice_name = iccid;
    deviceInfo.efairydevice_uuid = [NSString stringWithFormat:@"%@010101", iccid];
    deviceInfo.efairydevice_description = @"";
    deviceInfo.efairydevice_project_id = self.project_id;
    deviceInfo.efairydevice_install_time = [[NSDate date] xd_yyyy_MM_ddHHmmss];
    
    // 海普庆科技发展有限公司
    deviceInfo.efairydevice_location_lng = 113.813463;
    deviceInfo.efairydevice_location_lat = 22.755278;
    deviceInfo.efairydevice_address = @"深圳市宝安区共和第一工业区";
    
    NSMutableDictionary *pars = [deviceInfo yy_modelToJSONObject];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
//    NSLog(@"添加设备的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiPjtMgrDevice] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"添加设备(%ld)成功返回：%@", (long)cntIndex, responseObject);
        [hud hideAnimated:NO];
//        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"添加设备成功"];
//        temp.completionBlock = ^{
//            [self backToParent];
//        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"添加设备(%ld)失败：%@", (long)cntIndex, error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestEditDevice {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [self parametersDictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    NSLog(@"编辑设备的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiPjtMgrDevice] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"编辑设备返回：%@", responseObject);
        [hud hideAnimated:NO];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"编辑设备成功"];
        temp.completionBlock = ^{
            [self backToParent];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"编辑设备失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestDeviceDetail {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    [pars setObject:@(self.deviceItem.efairydevice_id) forKey:@"efairydevice_id"];
    [pars setObject:@(self.project_id) forKey:@"efairyproject_id"];
    NSLog(@"获取设备详情的参数 = %@", pars);
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiPjtMgrDevice] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"获取设备详情返回：%@", responseObject);
        [hud hideAnimated:NO];
        self.deviceItem = [EFADeviceListItem yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self.deviceItem refreshDeviceTypeName];
        self.dataArray = [self refreshDataArray];
        self.devPubModel = [[EFADevPubModel alloc] initWithImgUrlArray:self.deviceItem.efairydevice_imgurl_list canEdit:NO];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"获取设备详情失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)saveBarBtnItem {
    if (!_saveBarBtnItem) {
        _saveBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(addBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_saveBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _saveBarBtnItem;
}
- (UIBarButtonItem *)batchBarBtnItem {
    if (!_batchBarBtnItem) {
        _batchBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"批量" style:UIBarButtonItemStylePlain target:self action:@selector(batchBarBtnTapped:)];
    }
    return _batchBarBtnItem;
}
- (NSArray<NSArray<EFAPjtAddViewCfg *> *> *)dataArray {
    if (!_dataArray) {
        _dataArray = [self refreshDataArray];
    }
    return _dataArray;
}

- (NSArray<NSArray<EFAPjtAddViewCfg *> *> *)refreshDataArray {
    EFAPjtAddViewCfg *cfg1 = ({
        EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
        cfg.key = @"efairydevice_device_type_name";
        cfg.keyDes = @"设备类型";
        cfg.value = self.deviceItem.efairydevice_device_type_name;
        cfg.keyboardType = UIKeyboardTypeDefault;
        cfg.isInput = NO;
        cfg.isTextField = YES;
        cfg.valueMinLen = 1;
        cfg.valueMaxLen = 30;
        cfg.prompt = @"请选择设备类型";
        cfg.enabled = (self.viewType != EFAPjtDeviceAddVCTypeDetail);
        cfg.scanEnabled = NO;
        cfg;
    });
    
    EFAPjtAddViewCfg *cfg2 = ({
        EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
        cfg.key = @"efairydevice_main_uuid";
        cfg.keyDes = @"设备主编码";
        cfg.value = self.deviceItem.efairydevice_main_uuid;
        cfg.keyboardType = UIKeyboardTypeDefault;
        cfg.isInput = NO;
        cfg.isTextField = YES;
        cfg.valueMinLen = 20;
        cfg.valueMaxLen = 20;
        cfg.prompt = @"设备主编码长度为20个字符";
        cfg.enabled = (self.viewType != EFAPjtDeviceAddVCTypeDetail);
//        cfg.scanEnabled = (self.viewType != EFAPjtDeviceAddVCTypeDetail);
        cfg.scanEnabled = NO;
        cfg;
    });
    
    EFAPjtAddViewCfg *cfg3 = ({
        EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
        cfg.key = @"efairydevice_sub_uuid";
        cfg.keyDes = @"设备从编码";
        cfg.value = self.deviceItem.efairydevice_sub_uuid;
        cfg.keyboardType = UIKeyboardTypeDefault;
        cfg.isInput = NO;
        cfg.isTextField = YES;
        cfg.valueMinLen = 1;
        cfg.valueMaxLen = 11;
        cfg.prompt = @"设备从编码长度为6个字符";
        cfg.enabled = (self.viewType != EFAPjtDeviceAddVCTypeDetail);
        cfg.scanEnabled = NO;
        cfg;
    });
    
    EFAPjtAddViewCfg *cfg4 = ({
        EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
        cfg.key = @"efairydevice_name";
        cfg.keyDes = @"设备名称";
        cfg.value = self.deviceItem.efairydevice_name;
        cfg.keyboardType = UIKeyboardTypeDefault;
        cfg.isInput = YES;
        cfg.isTextField = YES;
        cfg.valueMinLen = 1;
        cfg.valueMaxLen = 24;
        cfg.prompt = @"设备名称长度最大为24个字符";
        cfg.enabled = (self.viewType != EFAPjtDeviceAddVCTypeDetail);
        cfg.scanEnabled = NO;
        cfg;
    });
    
    EFAPjtAddViewCfg *cfg5 = ({
        EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
        cfg.key = @"efairydevice_address";
        cfg.keyDes = @"设备定位";
        cfg.value = self.deviceItem.efairydevice_address;
        cfg.keyboardType = UIKeyboardTypeDefault;
        cfg.isInput = NO;
        cfg.isTextField = YES;
        cfg.valueMinLen = 1;
        cfg.valueMaxLen = 64;
        cfg.prompt = @"请选择设备定位";
        cfg.enabled = (self.viewType != EFAPjtDeviceAddVCTypeDetail);
        cfg.scanEnabled = NO;
        cfg;
    });
    
    EFAPjtAddViewCfg *cfg6 = ({
        EFAPjtAddViewCfg * cfg = [[EFAPjtAddViewCfg alloc] init];
        cfg.key = @"efairydevice_description";
        cfg.keyDes = @"设备描述";
        cfg.value = self.deviceItem.efairydevice_description;
        cfg.keyboardType = UIKeyboardTypeDefault;
        cfg.isInput = YES;
        cfg.isTextField = NO;
        cfg.valueMinLen = 0;
        cfg.valueMaxLen = 200;
        cfg.prompt = @"设备描述不能超过200个字符";
        cfg.enabled = (self.viewType != EFAPjtDeviceAddVCTypeDetail);
        cfg.scanEnabled = (self.viewType != EFAPjtDeviceAddVCTypeDetail);
        cfg;
    });
    
    
    return @[@[cfg1, cfg2, cfg3, cfg4, cfg5, cfg6]];
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}
@end
